﻿using System;
using System.IO;
using System.Linq;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Sykj.ViewModel;
using Sykj.Components;
using System.Collections.Generic;
using Sykj.IServices;
using Sykj.Infrastructure;

namespace Sykj.Web.Controllers
{
    /// <summary>
    /// 文件上传
    /// </summary>
    public class UploadController : Controller
    {
        IThumbnailSize _thumbnailSize;

        /// <summary>
        /// 
        /// </summary>
        public UploadController(IThumbnailSize thumbnailSize)
        {
            _thumbnailSize = thumbnailSize;
        }

        /// <summary>
        /// 生成文件名
        /// </summary>
        /// <remarks>
        /// </remarks>
        string GenerateFileName(string fileName)
        {
            return Guid.NewGuid().ToString("N").ToLower() + Path.GetExtension(fileName).ToLower();
        }

        /// <summary>
        /// 上传文件目录
        /// </summary>
        string UploadPath { get; set; } = $"/upload/";

        /// <summary>
        /// 允许上传图片后缀
        /// </summary>
        string[] allowFileExt = ".rar|.zip|.doc|.docx|.xls|.swf|.xlsx|.jpg|.jpeg|.gif|.png|.bmp".Split('|');

        /// <summary>
        /// 允许上传文件后缀
        /// </summary>
        string[] allowImagesExt = ".jpg|.png|.bmp|.gif".Split('|');

        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="type">所属模块</param>
        /// <returns></returns>
        public IActionResult Images(EnumHelper.UpLoadType type)
        {
            try
            {
                //接收上传文件
                IFormFile formFile = Request.Form.Files[0];
                if (formFile.Length <= 0)
                {
                    return Json(new ApiResult(false, "上传文件为空"));
                }

                //判断上传文件类型
                if (!allowImagesExt.Contains(Path.GetExtension(formFile.FileName).ToLower()))
                {
                    return Json(new ApiResult(false, "上传文件非法，格式不正确"));
                }

                //获取文件流转为字节
                byte[] byteData = FileHelper.ConvertStreamToByteBuffer(formFile.OpenReadStream());

                //判断是否为真实图片文件
                if (!FileHelper.IsImageFile(byteData))
                {
                    return Json(new ApiResult(false, "上传文件非法，非图片文件"));
                }

                //文件重命名
                string fileName = GenerateFileName(formFile.FileName);
                //获取文件扩展名
                string fileExt = Path.GetExtension(fileName).ToLower();
                //获取静态资源根路径
                string webRootPath = BaseConfig.WebRootPath;
                //保存路径
                string filePath = webRootPath + UploadPath;
                //存放目录
                string folder = type + "/" + DateTime.Now.ToString("yyyyMMdd") + "/";

                //读取缩略图生成配置
                List<Sykj.Entity.ThumbnailSize> list = _thumbnailSize.GetListByCache();
                if (list.Count > 0)
                {
                    var item = list.Where(c => c.ThumName == "ts_").FirstOrDefault();
                    //缩略图文件流
                    byte[] thumbData = ImageHelper.MakeThumbnailImage(byteData, fileExt, item.ThumWidth, item.ThumHeight);
                    //保存文件
                    FileHelper.SaveFile(thumbData, filePath + folder, fileName);
                }

                return Json(new ApiResult(true, "上传文件成功", 0, new { path = UploadPath + folder + fileName }, 0));
            }
            catch (Exception exc)
            {
                return Json(new ApiResult(false, "上传文件出错，错误原因：" + exc.ToString()));
            }
        }

        /// <summary>
        /// 上传图片并生成缩略图
        /// </summary>
        /// <param name="type">所属模块</param>
        /// <returns></returns>
        public IActionResult ImagesThumb(EnumHelper.UpLoadType type)
        {
            try
            {
                //接收上传文件
                IFormFile formFile = Request.Form.Files[0];
                if (formFile.Length <= 0)
                {
                    return Json(new ApiResult(false, "上传文件为空"));
                }

                //判断上传文件类型
                if (!allowImagesExt.Contains(Path.GetExtension(formFile.FileName).ToLower()))
                {
                    return Json(new ApiResult(false, "上传文件非法"));
                }

                //获取文件流转为字节
                byte[] byteData = FileHelper.ConvertStreamToByteBuffer(formFile.OpenReadStream());

                //判断是否为真实图片文件
                if (!FileHelper.IsImageFile(byteData))
                {
                    return Json(new ApiResult(false, "上传文件非法，非图片文件"));
                }

                //文件重命名
                string fileName = GenerateFileName(formFile.FileName);
                //获取文件扩展名
                string fileExt = Path.GetExtension(fileName).ToLower();
                //获取静态资源根路径
                string webRootPath = BaseConfig.WebRootPath;
                //保存路径
                string filePath = webRootPath + UploadPath;
                //存放目录
                string folder = type + "/" + DateTime.Now.ToString("yyyyMMdd") + "/";

                //保存原始上传文件
                FileHelper.SaveFile(byteData, filePath + folder, fileName);

                //读取缩略图生成配置
                List<Sykj.Entity.ThumbnailSize> list = _thumbnailSize.GetThumSizeList(type);
                if (list.Count > 0)
                {
                    foreach (var item in list)
                    {
                        //缩略图文件流
                        byte[] thumbData = ImageHelper.MakeThumbnailImage(byteData, fileExt, item.ThumWidth, item.ThumHeight, item.ThumMode);
                        //保存文件
                        FileHelper.SaveFile(thumbData, filePath + folder, item.ThumName + fileName);
                    }
                }

                return Json(new ApiResult(true, "上传文件成功", 0, new { path = UploadPath + folder + fileName, thumb = UploadPath + folder + "{0}" + fileName }, 0));
            }
            catch (Exception exc)
            {
                return Json(new ApiResult(false, "上传文件出错，错误原因：" + exc.ToString()));
            }
        }

        /// <summary>
        /// 上传普通文件
        /// </summary>
        /// <param name="type">所属模块</param>
        /// <returns></returns>
        public IActionResult Files(EnumHelper.UpLoadType type)
        {
            try
            {
                //接收上传文件
                IFormFile formFile = Request.Form.Files[0];
                if (formFile.Length <= 0)
                {
                    return Json(new ApiResult(false, "上传文件为空"));
                }

                //判断上传文件类型
                if (!allowFileExt.Contains(Path.GetExtension(formFile.FileName).ToLower()))
                {
                    return Json(new ApiResult(false, "上传文件非法"));
                }

                //文件重命名
                string fileName = GenerateFileName(formFile.FileName);

                //获取静态资源根路径
                string webRootPath = BaseConfig.WebRootPath;
                //存放目录
                string folder = type + "/" + DateTime.Now.ToString("yyyyMMdd") + "/";

                //判断目录是否存在
                string filePath = webRootPath + UploadPath + folder;
                if (!Directory.Exists(filePath))
                {
                    Directory.CreateDirectory(filePath);
                }

                using (var stream = new FileStream(filePath + fileName, FileMode.Create))
                {
                    formFile.CopyTo(stream);
                }

                return Json(new ApiResult(true, "上传文件成功", (int)ApiEnum.Status, new { path = UploadPath + folder + fileName }, 0));
            }
            catch (Exception exc)
            {
                return Json(new ApiResult(false, "上传文件出错，错误原因：" + exc.ToString()));
            }
        }
    }
}